package com.beijiteshop.shop.ui.search.vm

import androidx.lifecycle.MutableLiveData
import com.beijiteshop.libcommon.base.viewmodel.BaseViewModel
import com.beijiteshop.libcommon.network.ext.onBizEmpty
import com.beijiteshop.libcommon.network.ext.onBizError
import com.beijiteshop.libcommon.network.ext.onBizOK
import com.beijiteshop.libcommon.network.ext.serverData
import com.beijiteshop.libcommon.network.model.onFailure
import com.beijiteshop.libcommon.network.model.onSuccess
import com.beijiteshop.shop.model.entity.ProductItemEntity
import com.beijiteshop.shop.ui.search.repo.SearchRepo

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/16 14:53
 * @Description
 */
class SearchVM(private val repo: SearchRepo) : BaseViewModel(){

    val liveProducts = MutableLiveData<MutableList<ProductItemEntity>>()

    fun search(page: Int,key: String) = launch {
        repo.search(page, key)
            .serverData()
            .onSuccess {
                onBizOK { code, data, message ->
                    if (data?.data.isNullOrEmpty()){
                        liveEmpty.postValue(null)
                    }else{
                        val result = mutableListOf<ProductItemEntity>()
                        data!!.data!!.forEach {
                            result.add(ProductItemEntity(ProductItemEntity.TYPE_COMMON_GOODS,1,it))
                        }

                        liveProducts.postValue(result)
                    }
                }

                onBizError { code, message ->
                    liveError.postValue(message)
                }

                onBizEmpty {
                    liveEmpty.postValue(it)
                }
            }
            .onFailure {
                liveNetError.postValue(it.message)
            }

    }

}